import {defineStore} from 'pinia'
export const useUserStore = defineStore('user',{
    state:()=>{
        return{
            name:'Tom',
            age:19
        }
    },
    actions:{
        setAge(){
            this.age++;
        }
    },
    persist:{
        enabled:true,
        strategies:[{
            key:'user',
            storage:localStorage,
            // paths:['age']
        }


        ]
    }
})
export const useShopStore = defineStore('shop',{
    state:()=>{
        return{
            list:[
                { "id": 1,"title": "电水壶", "price": 50.01, src: "/static/1.jpg" },
                {"id": 2, "title": "电压力锅","price": 260.99, src: "/static/2.jpg" },
                { "id": 3, "title": "电饭煲", "price": 200.99, src: "/static/3.jpg" },
                {"id": 4, "title": "电磁炉","price": 300.99, src: "/static/4.jpg" },
                {"id": 5, "title": "微波炉", "price": 400.99, src: "/static/5.jpg" },
                { "id": 6, "title": "电饼铛", "price": 200.99, src: "/static/6.jpg" },
                {"id": 7, "title": "豆浆机", "price": 199.99, src: "/static/7.jpg" },
                { "id": 8, "title":"多用途锅","price": 510.99, src: "/static/8.jpg"}
              ],
              carts:[]
        }
    },
    getters:{
        getNum(state){
           
               return state.carts.reduce((s,item)=>s+item.num,0)
           
        },
        getTotal(state){
            return state.carts.reduce((total,item)=>total+item.price*item.num,0)
        }
        
    },
    actions:{
        setCartsSubNum(obj){
            const re = this.carts.find(item=>{
                if(item.id===obj.id){
                    if(item.num>1){
                        item.num--
                    }
                    else if(item.num==1){
                       this.carts = this.carts.filter(item=>item.id!==obj.id)
                    }                
                }
            });
        },
        setCartsAddNum(obj){
            const re = this.carts.find(item=>{
                if(item.id===obj.id){     
                        item.num++;                      
                }
            });
        },
       setCatrs(obj){
            // this.carts.push(obj)
           const re = this.carts.find(item=>item.id===obj.id);
           if(!re){
                const newObj = {
                    id:obj.id,
                    title:obj.title,
                    price:obj.price,
                    src:obj.src,
                    num:1
                }
                this.carts.push(newObj);
           }
           else{
                re.num++
           }

       },
     
    },
    persist:{
        enabled:true,
        strategies:[{
             key:'shop',
             storage:localStorage
        }
           

        ]
       }
})